package com.h3bpm.starcharge.service.impl.bpm;

import OThinker.Common.Data.BoolMatchValue;
import OThinker.Common.Organization.Models.User;
import OThinker.H3.Entity.Data.Attachment.Attachment;
import OThinker.H3.Entity.Data.Attachment.AttachmentHeader;
import OThinker.H3.Entity.Instance.Data.InstanceData;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.h3bpm.base.util.AppUtility;
import com.h3bpm.starcharge.common.bean.RetResponse;
import com.h3bpm.starcharge.common.bean.RetResult;
import com.h3bpm.starcharge.common.uitl.SqlUtils;
import com.h3bpm.starcharge.service.bpm.UserService;
import data.DataRow;
import data.DataTable;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.*;

/**
 * @author LLongAgo
 * @date 2019/5/8
 * @since 1.0.0
 */
@Service
public class UserServiceImpl implements UserService {

    private static final String DEFAULT_PASSWORD = "000000";

    /**
     * 新增用户
     *
     * @param instanceData InstanceData
     * @return RetResult
     * @throws Exception
     */
    @Override
    public RetResult addByExcel(InstanceData instanceData) throws Exception {
        List<Map<String, Object>> readAll = getExcelList(instanceData);
        for (Map<String, Object> map : readAll) {
            User user = new User();
            user.setName(map.get("姓名").toString());
            user.setIDNumber(map.get("工号").toString());
            user.setPassword(DEFAULT_PASSWORD);
            user.setMobile(map.get("手机号").toString());
            user.setCode(map.get("手机号").toString());
            user.setParentID(map.get("部门ID").toString());
            AppUtility.getEngine().getOrganization().AddUnit(User.AdministratorID, user);
        }
        return RetResponse.makeOKRsp();
    }

    /**
     * 变更部门
     *
     * @param instanceData InstanceData
     * @return RetResult
     * @throws Exception
     */
    @Override
    public RetResult changeDeptByExcel(InstanceData instanceData) throws Exception {
        List<Map<String, Object>> readAll = getExcelList(instanceData);
        for (Map<String, Object> map : readAll) {
            String code = map.get("手机号").toString();
            User user = AppUtility.getEngine().getOrganization().GetUserByCode(code);
            user.setParentID(map.get("新部门ID").toString());
            AppUtility.getEngine().getOrganization().UpdateUnit(User.AdministratorID, user);
        }
        return RetResponse.makeOKRsp();
    }

    /**
     * 返回Excel列表
     *
     * @param instanceData InstanceData
     * @return List<Map < String ,   Object>>
     * @throws Exception
     */
    private List<Map<String, Object>> getExcelList(InstanceData instanceData) throws Exception {
        AttachmentHeader header = AppUtility.getEngine().getBizObjectManager().QueryAttachment(
                instanceData.getSchemaCode(), instanceData.getBizObject().getObjectID(), "attr", BoolMatchValue.True, "").get(0);
        Attachment attr = AppUtility.getEngine().getBizObjectManager().GetAttachment(User.AdministratorID,
                instanceData.getSchemaCode(),
                instanceData.getBizObject().getObjectID(),
                header.getObjectID());
        InputStream sbs = new ByteArrayInputStream(attr.getContent());
        ExcelReader reader = ExcelUtil.getReader(sbs);
        return reader.readAll();
    }

    /**
     * 获取所有用户
     *
     * @return List<List   <   String>>
     * @throws Exception
     */
    @Override
    public List<List<String>> getAllUsers() throws Exception {
        List<List<String>> list = new ArrayList<>();
        DataTable dataTable = SqlUtils.doQuery("SELECT a.idnumber AS 'idnumber', a.Name AS 'name', a.Code AS 'tel', g.Name AS 'a', f.Name AS 'b', e.Name AS 'c', d.Name AS 'd', c.Name AS 'e', b.Name AS 'f' FROM OT_User a INNER JOIN ot_OrganizationUnit b ON a.ParentID = b.ObjectID AND a.code != 'Administrator' LEFT JOIN ot_OrganizationUnit c ON b.ParentID = c.ObjectID LEFT JOIN ot_OrganizationUnit d ON c.ParentID = d.ObjectID LEFT JOIN ot_OrganizationUnit e ON d.ParentID = e.ObjectID LEFT JOIN ot_OrganizationUnit f ON e.ParentID = f.ObjectID LEFT JOIN ot_OrganizationUnit g ON f.ParentID = g.ObjectID WHERE a.State = 1 ");
        if (dataTable.getRows().size() > 0) {
            for (int i = 0; i < dataTable.getRows().size(); i++) {
                DataRow dataRow = dataTable.getRows().get(i);
                String idNumber = dataRow.getString(0);
                String name = dataRow.getString(1);
                String tel = dataRow.getString(2);
                StringBuilder sb = new StringBuilder();
                for (int j = 3; j < 9; j++) {
                    String org = dataRow.getString(j);
                    if (!"Null".equals(org) && org != null) {
                        sb.append(org).append("/");
                    }
                }
                String orgName = sb.toString();
                orgName = orgName.substring(0, orgName.length() - 1);
                List<String> row = CollUtil.newArrayList(idNumber, name, tel, orgName);
                list.add(row);
            }
        }
        return list;
    }

    /**
     * 所有组织负责人
     * @return List<List < String>>
     * @throws Exception
     */
    @Override
    public List<List<String>> getDeptLeaders() throws Exception {
        List<List<String>> list = new ArrayList<>();
        DataTable dataTable = SqlUtils.doQuery("SELECT SUBSTRING(T.org, CHARINDEX('/我的公司', T.org), 1000) AS 'org', a.Name AS 'name' from (SELECT ISNULL(g.Name, '')+'/'+ISNULL(f.Name, '')+'/'+ISNULL(e.Name, '')+'/'+ISNULL(d.Name, '')+'/'+ISNULL(c.Name, '')+'/'+ISNULL(b.Name, '') as org,b.ManagerID FROM ot_OrganizationUnit b LEFT JOIN ot_OrganizationUnit c ON b.ParentID = c.ObjectID LEFT JOIN ot_OrganizationUnit d ON c.ParentID = d.ObjectID LEFT JOIN ot_OrganizationUnit e ON d.ParentID = e.ObjectID LEFT JOIN ot_OrganizationUnit f ON e.ParentID = f.ObjectID LEFT JOIN ot_OrganizationUnit g ON f.ParentID = g.ObjectID) T LEFT JOIN OT_User a ON a.ObjectID = T.ManagerID AND a.code != 'Administrator' ORDER BY T.org");
        if (dataTable.getRows().size() > 0) {
            for (int i = 0; i < dataTable.getRows().size(); i++) {
                DataRow dataRow = dataTable.getRows().get(i);
                String org = dataRow.getString(0);
                String name = dataRow.getString(1);
                if (!"Null".equals(name) && name != null) {
                    List<String> row = CollUtil.newArrayList(org, name);
                    list.add(row);
                }
            }
        }
        return list;
    }

    /**
     * 所有部门ID
     * @return List<List < String>>
     * @throws Exception
     */
    @Override
    public List<List<String>> getDeptObjects() throws Exception {
        List<List<String>> list = new ArrayList<>();
        DataTable dataTable = SqlUtils.doQuery("SELECT g.name AS 'a', g.ObjectID AS 'ao', f.name AS 'b', f.ObjectID AS 'bo', e.name AS 'c', e.ObjectID AS 'co', d.name AS 'd', d.ObjectID AS 'do', c.Name AS 'e', c.ObjectID AS 'eo', b.Name AS 'f', b.Objectid AS 'fo' FROM ot_OrganizationUnit b LEFT JOIN ot_OrganizationUnit c ON b.ParentID = c.ObjectID LEFT JOIN ot_OrganizationUnit d ON c.ParentID = d.ObjectID LEFT JOIN ot_OrganizationUnit e ON d.ParentID = e.ObjectID LEFT JOIN ot_OrganizationUnit f ON e.ParentID = f.ObjectID LEFT JOIN ot_OrganizationUnit g ON f.ParentID = g.ObjectID");
        if (dataTable.getRows().size() > 0) {
            for (int i = 0; i < dataTable.getRows().size(); i++) {
                DataRow dataRow = dataTable.getRows().get(i);
                List<String> row = new ArrayList<>();
                for (int j = 0; j < 12; j++) {
                    String field = dataRow.getString(j);
                    if (!"Null".equals(field) && field != null) {
                        row.add(field);
                    }
                }
                list.add(row);
            }
        }
        return list;
    }

    /**
     * 获取员工角色
     * @param objectId  员工id
     * @return RetResult
     * @throws Exception
     */
    @Override
    public RetResult getUserPost(String objectId) throws Exception {
        List<Map<String, String>> list = new ArrayList<>();
        DataTable dataTable = SqlUtils.doQuery("SELECT p.Name FROM OT_OrgStaff AS s INNER JOIN OT_OrgPost AS p ON s.ParentObjectID = p.ObjectID WHERE s.UserID = '" + objectId + "'");
        if (dataTable.getRows().size() > 0) {
            for (int i = 0; i < dataTable.getRows().size(); i++) {
                DataRow dataRow = dataTable.getRows().get(i);
                Map<String, String> map = new HashMap<>(2);
                map.put("post", dataRow.getString(0));
                list.add(map);
            }
        }
        return RetResponse.makeOKRsp(list);
    }
}